package com.justonetech.translation.controller;

import com.justonetech.core.controller.BaseCRUDActionController;
import com.justonetech.core.orm.hibernate.Page;
import com.justonetech.core.orm.hibernate.QueryTranslate;
import com.justonetech.core.ui.grid.Grid;
import com.justonetech.core.utils.ReflectionUtils;
import com.justonetech.system.daoservice.SysDeptService;
import com.justonetech.system.daoservice.SysPersonService;
import com.justonetech.system.domain.SysDept;
import com.justonetech.system.domain.SysPerson;
import com.justonetech.system.tree.Node;
import com.justonetech.system.tree.TreeBranch;
import com.justonetech.system.tree.ZTreeNode;
import com.justonetech.translation.daoservice.ContractService;
import com.justonetech.translation.domain.Contract;
import com.justonetech.translation.domain.Project;
import com.justonetech.translation.manager.ContractManager;
import com.lowagie.text.DocumentException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @version 1.0
 * @author: System
 */
@Controller
public class ContractController extends BaseCRUDActionController<Contract> {
    private static Log log = LogFactory.getLog(ContractController.class);

    @Autowired
    private ContractService contractService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysPersonService sysPersonService;

    @Autowired
    private ContractManager contractManager;

    @RequestMapping
    @ResponseBody
    public Page<Contract> grid(Page page, String condition) {
        try {
            page.setAutoCount(true);

            String hql = "from Contract t where 1=1 " ;

            QueryTranslate queryTranslate = new QueryTranslate(hql, condition);

            // 查询
            page = contractService.findByPage(page, queryTranslate.toString());
        } catch (Exception e) {
            log.error("error", e);
        }

        return page;
    }

    @RequestMapping
    public String init(Model model, Contract entity) throws Exception {
        try {
            if(entity != null && entity.getId() != null) {
                entity = contractService.get(entity.getId());

                model.addAttribute("bean", entity);
            }
        } catch (Exception e) {
            log.error("error", e);
        }
        return "view/cont/contractEdit";
    }

    @RequestMapping
    public String view(Model model, Long id) {
        Contract contract = contractService.get(id);

        model.addAttribute("bean", contract);
        return "view/cont/contractView";
    }

    @RequestMapping
    public void save(HttpServletResponse response, Model model, @ModelAttribute("bean") Contract entity)
            throws Exception {
        try {
            String[] columns = new String[]{
                    "id",
                    "project",
                    "name",
                    "code",
                    "firstParty",
                    "secondParty",
                    "fisrtSignDate",
                    "secondSignDate",
                    "price",
                    "professionalFee",
                    "urgentFee",
                    "typesettingFee",
                    "advancePayment",
                    "moneyAmount",
                    "remark",
                    "isValid"
            };

            Contract target;
            if (entity.getId() != null) {
                target = contractService.get(entity.getId());

                ReflectionUtils.copyBean(entity, target, columns);
            } else {
                target = entity;
            }

            contractService.save(target);
            sendSuccessJSON(response, "保存成功");
        } catch (Exception e) {
            log.error("error", e);
            super.processException(response, e);
        }
    }

    @RequestMapping
    public void delete(HttpServletResponse response, Long id) throws Exception {
        contractService.delete(id);

        sendSuccessJSON(response, "删除成功");
    }

    @RequestMapping
    @ResponseBody
    public List<Node> getFirst(String type,String uid, String id) throws Exception {
        TreeBranch treeBranch = new TreeBranch();
        type = StringUtils.defaultString(type, "");

        if(StringUtils.isEmpty(uid)) {
            ZTreeNode treeNode = new ZTreeNode();
            treeNode.setId("root");
            treeNode.setIsParent(true);
            treeNode.setIsLeaf(false);
            treeNode.setOpen(true);
            treeNode.setName("单位部门树");
            treeNode.setText("单位部门树");
            treeNode.setUid("root");
            treeBranch.addTreeNode(treeNode);
        } else if("root".equals(id)){
            String hql = "from SysDept where code='MANAGER'";

            if (!StringUtils.equals(uid, "root")) {
                hql = "from SysDept where parent.id = " + uid + " order by treeId";
            }

            List<SysDept> sysDepts = sysDeptService.findByQuery(hql);

            for (SysDept sysDept : sysDepts) {
                ZTreeNode treeNode = new ZTreeNode();
                treeNode.setId(sysDept.getClass().getSimpleName() + "_" + sysDept.getId());
                if(sysDept.getIsLeaf() != null && !sysDept.getIsLeaf()){
                    treeNode.setIsParent(true);
                    treeNode.setOpen(false);
                }else{
                    treeNode.setIsLeaf(true);
                }
                treeNode.setName(sysDept.getName());
                treeNode.setText(sysDept.getName());
                treeNode.setUid(sysDept.getId().toString());
                treeNode.setType(sysDept.getClass().getSimpleName());
                treeNode.setTreeId(sysDept.getTreeId());
                treeBranch.addTreeNode(treeNode);
            }
        } else if(id.contains("SysDept")){
            List<SysPerson> sysPersons = sysPersonService.findByQuery("from SysPerson p where p.dept.id="+uid);

            for (SysPerson sysPerson : sysPersons) {
                ZTreeNode treeNode = new ZTreeNode();
                treeNode.setId(sysPerson.getClass().getSimpleName() + "_" + sysPerson.getId());
                treeNode.setIsLeaf(true);
                treeNode.setName(sysPerson.getName());
                treeNode.setText(sysPerson.getName());
                treeNode.setUid(sysPerson.getId().toString());
                treeNode.setType(sysPerson.getClass().getSimpleName());
                treeBranch.addTreeNode(treeNode);
            }
        }

        return treeBranch.getTreeNodeList();
    }

    @RequestMapping
    @ResponseBody
    public List<Node> getSecond(String type,String uid, String id) throws Exception {
        TreeBranch treeBranch = new TreeBranch();
        type = StringUtils.defaultString(type, "");

        if(StringUtils.isEmpty(uid)) {
            ZTreeNode treeNode = new ZTreeNode();
            treeNode.setId("root");
            treeNode.setIsParent(true);
            treeNode.setIsLeaf(false);
            treeNode.setOpen(true);
            treeNode.setName("单位部门树");
            treeNode.setText("单位部门树");
            treeNode.setUid("root");
            treeBranch.addTreeNode(treeNode);
        } else if("root".equals(id)){
            String hql = "from SysDept where parent.id is null order by treeId";

            if (!StringUtils.equals(uid, "root")) {
                hql = "from SysDept where parent.id = " + uid + " order by treeId";
            }

            List<SysDept> sysDepts = sysDeptService.findByQuery(hql);

            for (SysDept sysDept : sysDepts) {
                ZTreeNode treeNode = new ZTreeNode();
                treeNode.setId(sysDept.getClass().getSimpleName() + "_" + sysDept.getId());
                if(sysDept.getIsLeaf() != null && !sysDept.getIsLeaf()){
                    treeNode.setIsParent(true);
                    treeNode.setOpen(false);
                }else{
                    treeNode.setIsLeaf(true);
                }
                treeNode.setName(sysDept.getName());
                treeNode.setText(sysDept.getName());
                treeNode.setUid(sysDept.getId().toString());
                treeNode.setType(sysDept.getClass().getSimpleName());
                treeNode.setTreeId(sysDept.getTreeId());
                treeBranch.addTreeNode(treeNode);
            }
        } else if(id.contains("SysDept")){
            List<SysPerson> sysPersons = sysPersonService.findByQuery("from SysPerson p where p.dept.id="+uid);

            for (SysPerson sysPerson : sysPersons) {
                ZTreeNode treeNode = new ZTreeNode();
                treeNode.setId(sysPerson.getClass().getSimpleName() + "_" + sysPerson.getId());
                treeNode.setIsLeaf(true);
                treeNode.setName(sysPerson.getName());
                treeNode.setText(sysPerson.getName());
                treeNode.setUid(sysPerson.getId().toString());
                treeNode.setType(sysPerson.getClass().getSimpleName());
                treeBranch.addTreeNode(treeNode);
            }
        }

        return treeBranch.getTreeNodeList();
    }

    @RequestMapping
    public void export(HttpServletResponse response,Long documentId,Long id) throws IOException {
        Contract contract = contractService.get(id);
        String fileName = contract.getName()+".doc";
        fileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
        response.reset();
        response.setContentType("vnd.ms-word; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        ServletOutputStream outputStream = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        try {
            contractManager.createDocContext(outputStream, contract,new SysPerson());
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally {
            bos.flush();
            bos.close();
        }
    }
}